package cn.xuanxuanyuhua.crm.web.controller;


import cn.xuanxuanyuhua.crm.domain.Department;
import cn.xuanxuanyuhua.crm.domain.Employee;
import cn.xuanxuanyuhua.crm.query.EmployeeQueryObject;
import cn.xuanxuanyuhua.crm.service.IDepartmentService;
import cn.xuanxuanyuhua.crm.service.IEmployeeService;
import cn.xuanxuanyuhua.crm.service.IRoleService;
import cn.xuanxuanyuhua.crm.util.JSONResult;
import lombok.Cleanup;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;

    @RequestMapping("/list")
    public String list(Model m, @ModelAttribute("qo")EmployeeQueryObject qo){
        m.addAttribute("pageInfo", employeeService.query(qo));
        m.addAttribute("departmentList", departmentService.list());
        return "/employee/list";
    }

    @RequiresPermissions(value = {"员工编辑","employee:input"},logical = Logical.OR)
    @RequestMapping("/input")
    public String input(Model m, Long id){
        if (id != null) {
            System.out.println(employeeService.get(id));
            m.addAttribute("entity", employeeService.get(id));
        }
        m.addAttribute("departmentList", departmentService.list());
        m.addAttribute("roleList", roleService.list());
        return "/employee/input";
    }

    @RequiresPermissions(value = {"员工新增/保存","employee:saveOrUpdate"},logical = Logical.OR)
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee entity, Long[] ids){
        employeeService.saveOrUpdate(entity,ids);
        return "redirect:/employee/list.do";
    }
    @RequiresPermissions(value = {"员工删除","employee:delete"},logical = Logical.OR)
    @RequestMapping("/delete")
    public String delete(Long id){
        employeeService.delete(id);
        return "redirect:/employee/list.do";
    }

    @RequiresPermissions(value = {"员工批量删除","employee:bacthDelete"},logical = Logical.OR)
    @RequestMapping("/batchDelete")
    @ResponseBody
    public Object batchDelete(Long[] ids){
        employeeService.batchDelete(ids);
        return new JSONResult();

    }

    @RequestMapping("/checkUsername")
    @ResponseBody
    public Boolean check(String name){
        return employeeService.checkUsernamae(name);
    }

    @RequestMapping("/export")
    public ModelAndView export(HttpServletResponse response) throws IOException {
        List<Employee> list = employeeService.list();
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet();
        Row row = sheet.createRow(0);
        Cell cell =row.createCell(0);
        cell.setCellValue("姓名");
        cell = row.createCell(1);
        cell.setCellValue("邮箱");
        cell =row.createCell(2);
        cell.setCellValue("年龄");
        cell =row.createCell(3);
        cell.setCellValue("部门");
        int index = 1;
        for (Employee employee : list) {
            row = sheet.createRow(index++);
            cell =row.createCell(0);
            cell.setCellValue(employee.getName());
            cell = row.createCell(1);
            cell.setCellValue(employee.getEmail());
            cell =row.createCell(2);
            cell.setCellValue(employee.getAge());
            cell =row.createCell(3);
            cell.setCellValue(employee.getDepartment().getName());
        }
        wb.write(response.getOutputStream());
        return null;
    }

    /**
     * @param xls 与上传时name属性值相同
     * @return
     * @throws IOException
     */
    @RequestMapping("/importExcel")
    public String importExcel(MultipartFile xls) throws IOException {
        if (!xls.isEmpty() && (xls.getSize() > 0) && (xls.getContentType().equals("application/vnd.ms-excel"))) {
            @Cleanup
            InputStream inputStream = xls.getInputStream();
            Workbook wb = new HSSFWorkbook(inputStream);
            Sheet sheetAt = wb.getSheetAt(0);
            int lastRowNum = sheetAt.getLastRowNum();
            Department dept = new Department();
            dept.setId(2L);
            for(int i = 1; i <= lastRowNum ; i ++){
                Row row = sheetAt.getRow(i);
                Cell cell = row.getCell(0);
                String name = cell.getStringCellValue();
                cell = row.getCell(1);
                String email = cell.getStringCellValue();
                cell = row.getCell(2);
                Double age = cell.getNumericCellValue();
                Employee employee = new Employee(name,"1",email,age.intValue(),false,dept,null,null);
                employeeService.saveOrUpdate(employee,null);
            }
        }
        return "redirect:/employee/list.do";
    }


    @RequestMapping("/emps")
    @ResponseBody
    public Object emps(Long id){
        return employeeService.selectEmpsById(id);
    }
}
